package com.videostreaming.controller;

import com.videostreaming.controller.base.BaseDbController;
import com.gooddies.wiring.annotations.WiringComponent;
import com.videostreaming.data.User;
import com.wiringweb.annotations.Controller;
import com.wiringweb.annotations.UrlBinding;
import com.wiringweb.data.FormData;
import com.wiringweb.http.HttpMethod;
import com.wiringweb.parameterprocessor.annotation.PathVariable;
import com.wiringweb.parameterprocessor.annotation.QueryParameter;
import com.wiringweb.resolution.JsonResolution;
import com.wiringweb.resolution.PlainTextResolution;
import com.wiringweb.resolution.RedirectResolution;
import com.wiringweb.resolution.Resolution;
import com.wiringweb.resolution.VelocityResolution;

/**
 * @author sad
 */
@Controller
@WiringComponent(singleton = true)
public class LoginController extends BaseDbController {

    @UrlBinding("/signin\\.html")
    public Resolution signinShow() {
        return new VelocityResolution("signin.vm");
    }

    @UrlBinding("/restlogin/(.*?)/(.*?)\\.html")
    public Resolution restLogin(@PathVariable String email, @PathVariable String password) {
        User user = getDb().getUserByEmailAndPassword(email, password);
        if (user != null) {
            return new JsonResolution(user);
        }else{
            return new PlainTextResolution(403,"User is not found");
        }
    }

    @UrlBinding(httpMethod = HttpMethod.POST, value = "/signin\\.html")
    public Resolution login(FormData formData) {
        String email = (String) formData.getArgument("email");
        String password = (String) formData.getArgument("password");
        User user = getDb().getUserByEmailAndPassword(email, password);
        if (user != null) {
            addSessionParameter("loggedUser", user);
            return new RedirectResolution("main.html");
        }else{
            addRequestParameter("userNotFound", true);
            addRequestParameter("email", email);
            return new VelocityResolution("signin.vm");
        }
    }

    @UrlBinding(value = "/logout\\.html")
    public Resolution logout() {
        removeSessionParameter("loggedUser");
        return new RedirectResolution("main.html");
    }
}
